package com.qcu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcu.dto.LoginDto;
import com.qcu.entity.StaffAccount;
import com.qcu.entity.User;
import com.qcu.service.LoginService;
import com.qcu.service.UserService;
import com.qcu.util.JwtUtil;
import com.qcu.util.PasswordUtils;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Name: MyComputer
 * @ClassName PlainLoginServiceImpl
 * @Description:
 * @date 2025/2/7 9:54
 */
@Service("PlainLoginService")
public class PlainLoginServiceImpl implements LoginService {
    @Resource
    UserService userService;
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Response login(LoginDto loginDto) {
        LambdaQueryWrapper<User> staffAccount = new LambdaQueryWrapper<>();
        staffAccount.eq(User::getUsername, loginDto.getUsername());
        User one = userService.getOne(staffAccount);
        if (one == null) {
            return Response.failure(ResponseCode.FAILURE, "用户名不存在");
        }
        if (!PasswordUtils.verifyPassword(loginDto.getPassword(), one.getSalt(), one.getPasswordHash())) {
            return Response.failure(ResponseCode.FAILURE, "密码错误");
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put("username",one.getUsername());
        claim.put("type","USER");
        claim.put("id",one.getId());
        claim.put("role","USER");
        String token = JwtUtil.genToken(claim);
        redisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);
        return Response.success(token);
    }
}
